package com.cskaoyan.weixin.controller;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.weixin.bean.login.WxLoginBO;
import com.cskaoyan.weixin.bean.login.WxLoginVO;
import com.cskaoyan.weixin.bean.login.WxLoginVO1;
import com.cskaoyan.realm.MallToken;
import com.cskaoyan.weixin.service.WxAuthenticateService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/wx/auth")
public class WxAuthenticateController {

    @Autowired
    WxAuthenticateService wxAuthenticateService;

    @RequestMapping("/login")
    public BaseRespVo login(@RequestBody WxLoginBO wxLoginBO) {
        Subject subject = SecurityUtils.getSubject();
        String username = wxLoginBO.getUsername();
        String password = wxLoginBO.getPassword();
        MallToken mallToken = new MallToken(username,password,"wx");
        try {
            subject.login(mallToken);
        } catch (AuthenticationException e) {
            return BaseRespVo.fail(700,"账号密码不对");
        }
        String id = (String) subject.getSession().getId();
        WxLoginVO wxLoginVO = new WxLoginVO();
        wxLoginVO.setToken(id);
        wxLoginVO.setTokenExpire(new Date());
        WxLoginVO1 userInfo = wxAuthenticateService.getUserInfo(username);
        wxLoginVO.setUserInfo(userInfo);
        return BaseRespVo.ok(wxLoginVO);
    }

    @RequestMapping("logout")
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }



}
